﻿#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;

#endregion

namespace VisualWebGuiApplication2
{
    public partial class TankInvoiceWithMony : UserControl
    {
        int lastid = 0;
      /*  BindingSource _bsTankOpen;
        GazOnDevEntities db2 = new GazOnDevEntities();*/
        Configdb dbconf;
         Tank_Stocks tanktofix;
        bool havetank=false;
        bool edit = false;
      //   Invoice selected;
        BindingList<invoiceitems2> _currentinvoiceitems = new BindingList<invoiceitems2>();
         Invoices2 _currentinvoice = new Invoices2();
         public TankInvoiceWithMony()
        {
            InitializeComponent();

          dataGridView1.CellClick+=new DataGridViewCellEventHandler(dataGridView1_CellClick);

          dataGridView1.KeyDown += new KeyEventHandler(dataGridView1_KeyDown);
          dataGridView1.AllowUserToAddRows = true;
          dataGridView1.ReadOnly = false;
          dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
             this.RightToLeft = Gizmox.WebGUI.Forms.RightToLeft.Yes;
            txtinvoiceid.Leave += new EventHandler(txtinvoiceid_Leave);
          //  txtTankNymber.Leave += new EventHandler(txtTankNymber_Leave);

        
            using (GazOnDevEntities db= new GazOnDevEntities())
            {
               

                 dbconf= db.Configdbs.FirstOrDefault();
                txtinvoiceid.Text = dbconf.invoicelastid2;
                txtcreatedby.Text = string.Format("{0}", Session["username"]);
                // must icrease id of invoice id  ;
            }
          //  textBox1.Leave += new EventHandler(textBox1_Leave);
           
        }

         void dataGridView1_KeyDown(object objSender, KeyEventArgs e)
         {
             dataGridView1.AllowUserToAddRows = true;
             if (e.KeyCode == Keys.Space)
             {
                 // e.Handled = true;
                 if (dataGridView1.CurrentCell.ColumnIndex == 2)
                 {
                     return;
                 }
                 if (dataGridView1.CurrentCell.ColumnIndex == 4)
                 {
                     return;
                 }
                 DataGridViewCell cell = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex];
                 dataGridView1.CurrentCell = cell;
                 dataGridView1.CurrentCell.ReadOnly = false;
                 dataGridView1.BeginEdit(true);
             }

         }

        

         public TankInvoiceWithMony(string invoiceid)
         {
             InitializeComponent();

           
             dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);

             dataGridView1.KeyDown += new KeyEventHandler(dataGridView1_KeyDown);
             dataGridView1.AllowUserToAddRows = true;
             dataGridView1.ReadOnly = false;
             dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
             this.RightToLeft = Gizmox.WebGUI.Forms.RightToLeft.Yes;
             this.RightToLeft = Gizmox.WebGUI.Forms.RightToLeft.Yes;
             txtinvoiceid.Leave += new EventHandler(txtinvoiceid_Leave);
           //  txtTankNymber.Leave += new EventHandler(txtTankNymber_Leave);
             txtinvoiceid.Text = invoiceid;
             EventArgs ev=new EventArgs();

             txtinvoiceid_Leave(txtinvoiceid, ev);
             /*using (GazOnDevEntities db = new GazOnDevEntities())
             {
               
                       _currentinvoice = db.Invoices.FirstOrDefault(x => x.invoiceNumber == invoiceid);

               
                 // must icrease id of invoice id  ;
             }*/
             //  textBox1.Leave += new EventHandler(textBox1_Leave);

         }
         private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
         {
             // delete gridview row  
             if (e.ColumnIndex == 0)
             {
                // MessageBox.Show(string.Format("CellClick Row={0} Col={1} DataSourceCheckBoxValue={2}", e.RowIndex, e.ColumnIndex, e.ColumnIndex) + Environment.NewLine);
                string ctype=string.Empty,dttype=string.Empty;
                  if(null!=dataGridView1.Rows[e.RowIndex].Cells["dttype"])
                  {
                  ctype=dataGridView1.Rows[e.RowIndex].Cells["dttype"].ToString();
                  }

                 if(null!=dataGridView1.Rows[e.RowIndex].Cells["dttypeid"])
                  {
                  dttype=dataGridView1.Rows[e.RowIndex].Cells["dttypeid"].ToString();
                  }
                 if (ctype == "tank")
                 {
                     updateTankStock(dttype, "");
                 
                 }
                 dataGridView1.Rows.RemoveAt(e.RowIndex);
                
                
             }

             /*else
                 MessageBox.Show(string.Format("CellClick Row={0} Col={1}", e.RowIndex, e.ColumnIndex) + Environment.NewLine);*/
         }

         void txtinvoiceid_Leave(object sender, EventArgs e)
         {
             using (GazOnDevEntities db = new GazOnDevEntities())
             {
                 _currentinvoice = db.Invoices2.FirstOrDefault(x => x.invoiceNumber == txtinvoiceid.Text);
                 if ((null != _currentinvoice) && (_currentinvoice.id > 0))
                 {
                     edit = true;
                     MessageBox.Show("תעודת משלוח עם מספר כזה קיימת  אתה עובר למצב תצוגה");
                   //  havetank = Convert.ToBoolean(_currentinvoice.havetank);
                     // set buttun to disable 
                     //button1.Enabled = false;
                     //btnReportPrint.Enabled = false;
                     //btnPrint.Enabled = false;
                     //btnupload.Enabled = false;
                     //foreach (Control item in dataGridView1.Controls)
                     //{
                     //    item.Enabled = false;
                         
                     //}
                     /*foreach (Control item in this.Controls)
                     {
                         item.Enabled = false;
                     }*/
                     dataGridView1.Enabled = false;
                     button1.Enabled = false;
                     btnPrint.Enabled = true;

                     txtAddress.Text = _currentinvoice.address;
                     txtTo.Text = _currentinvoice.C_to;
                     txtCarNum.Text = _currentinvoice.carnum;
                     DatetimePicker.Value = Convert.ToDateTime(_currentinvoice.date);
                     txtinvoiceid.Text = _currentinvoice.invoiceNumber;
                     txtCarTransporter.Text = _currentinvoice.transporter;
                 //    txtTankNymber.Text = _currentinvoice.tankNumber;
                     txtNotes.Text = _currentinvoice.tankDesc;
                     if (string.IsNullOrEmpty(_currentinvoice.createdby))
                     {
                         txtcreatedby.Text = string.Format("{0}", Session["username"]);
                     }
                     else
                     {
                         txtcreatedby.Text = _currentinvoice.createdby;
                     }
                     // increase invoice id number

                     var query = from p in db.invoiceitems2
                                 where p.invoiceid == txtinvoiceid.Text
                                 orderby p.id ascending
                                 select p;
                     _currentinvoiceitems = new BindingList<invoiceitems2>(query.ToList<invoiceitems2>());

                     //dataGridView1.AllowUserToAddRows = false;
                     //dataGridView1.AllowUserToDeleteRows = false;

                     //foreach (DataGridViewRow item in dataGridView1.Rows)
                     //{
                     //    dataGridView1.Rows.RemoveAt(item.Index);
                     //}
                     while (dataGridView1.Rows.Count > 1)
                     {
                         dataGridView1.Rows.RemoveAt(0);
                     }
                     //dataGridView1.Rows = new DataGridViewRowCollection(new DataGridView());
                     //DataGridViewRowCollection rows = new DataGridViewRowCollection(n);
               
   
                     //dataGridView1.AllowUserToAddRows = true;
                     //dataGridView1.AllowUserToDeleteRows = true;


                     foreach (var ctrl in _currentinvoiceitems)
                     {

                         int i;
                         i = dataGridView1.Rows.Add(new DataGridViewRow());
                         DataGridViewRowCollection cools;
                        
                         DataGridViewCell cell1 = new DataGridViewTextBoxCell();
                         cell1.Value = ctrl.title;
                         //"צובר " + ctrl.tankSize + " גלון מספר " + ctrl.TankNumber + "";
                         dataGridView1.Rows[i].Cells["dtclmnTitle"] = cell1;



                         cell1 = new DataGridViewTextBoxCell();
                         cell1.Value = ctrl.note;
                         dataGridView1.Rows[i].Cells["dtclmnNote"] = cell1;



                         DataGridViewButtonCell cell2 = new DataGridViewButtonCell();
                         cell2.Value = "מחיקה";
                         dataGridView1.Rows[i].Cells["dtbttndelet"] = cell2;



                         cell1 = new DataGridViewTextBoxCell();
                         cell1.Value = ctrl.amount;

                         dataGridView1.Rows[i].Cells["dtclmnAmount"] = cell1;

                         cell1 = new DataGridViewTextBoxCell();
                         cell1.Value = i + 1;
                         dataGridView1.Rows[i].Cells["dtclmnid"] = cell1;


                         cell1 = new DataGridViewTextBoxCell();
                         cell1.Value = ctrl.type;

                         dataGridView1.Rows[i].Cells["dttype"] = cell1;

                         cell1 = new DataGridViewTextBoxCell();
                         cell1.Value = ctrl.typeid;

                         dataGridView1.Rows[i].Cells["dttypeid"] = cell1;





                     }

                 }
                 else
                 { 
                 
                 // set buttns to enable 
                     edit = false;
                     foreach (Control item in this.Controls)
                     {
                         item.Enabled = true;
                     }
                    
                        //btnReportPrint.Enabled = true;
                        // btnPrint.Enabled = true;
                        // btnupload.Enabled = true;
                        // button1.Enabled = true;
                        // havetank = false;
                        // foreach (Control item in dataGridView1.Controls)
                        // {
                        //     item.Enabled = true;

                        // }

	               
                 }
             }
         }

        


       


   
     
     

    
        private void btnOpenTank_Click(object sender, EventArgs e)
        {
          
           

          
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("button1_Click");
        }

        private void btnupload_Click(object sender, EventArgs e)
        {
            MessageBox.Show("btnupload_Click");
        }

        private void btnReportPrint_Click(object sender, EventArgs e)
        {
            if (edit)
            {
               // MessageBox.Show("מצב עריכה");
            //    return;
            }
            using (GazOnDevEntities db = new GazOnDevEntities())
            {

                if (!edit)
                {
                    List<invoiceitems2> neweditlist = new List<invoiceitems2>();

                    foreach (var item in _currentinvoiceitems)
                    {
                        item.invoiceid = txtinvoiceid.Text;
                        try
                        {
                            db.AddToinvoiceitems2(item);
                        }
                        catch
                        {

                            neweditlist.Add(item);
                        }
                    }
                }
                //}

                if (_currentinvoice == null)
                {
                    _currentinvoice = new Invoices2();
                }
                _currentinvoice.address = txtAddress.Text;
                _currentinvoice.C_to = txtTo.Text;
                _currentinvoice.carnum = txtCarNum.Text;
                _currentinvoice.date = DatetimePicker.Value;
                _currentinvoice.invoiceNumber = txtinvoiceid.Text;
                _currentinvoice.createdby = txtcreatedby.Text;
               // _currentinvoice.tankNumber = tanktofix.TankNumber;
                _currentinvoice.tankDesc = txtNotes.Text;
                // increase invoice id number
                _currentinvoice.transporter = txtCarTransporter.Text;

                dbconf.invoicelastid2 = (Convert.ToInt32(dbconf.invoicelastid2) + 1).ToString();
                db.Attach(dbconf);
                db.ObjectStateManager.ChangeObjectState(dbconf, EntityState.Modified);
                if (!edit)
                {
                    db.AddToInvoices2(_currentinvoice);
                }
                else
                {
                    db.Attach(_currentinvoice);
                    db.ObjectStateManager.ChangeObjectState(_currentinvoice, EntityState.Modified);
                }
           
                if (db.SaveChanges() > 0)
                {



                    // MessageBox.Show("פעולת ההוספה הצליחה");
                    frmReportTankRecipet tanko = new frmReportTankRecipet(Convert.ToInt32(_currentinvoice.invoiceNumber), "report4");
                    tanko.ShowDialog();
                    //btnOpenTank.Enabled = false;

                }
                else
                {
                    MessageBox.Show("פעולת ההוספה נכשלה");

                }
            }
          //  btnOpenTank.Enabled = false;
          /*  frmReportTankRecipet tanko = new frmReportTankRecipet(tanktofix.Id, "report3");
            tanko.ShowDialog();*/
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
          /*  MessageBox.Show("button1_Click_1");*/
            InvoiceControlAccompanyStockAdd dd = new InvoiceControlAccompanyStockAdd();
            dd.FormClosing +=new Gizmox.WebGUI.Forms.Form.FormClosingEventHandler(dd_FormClosing);

          
            dd.ShowDialog();

            
          
        }

        void dd_FormClosing(object sender, FormClosingEventArgs e)
        {

                 /* dtclmnid;
        dtclmnTitle;
        dtclmnAmount;
   dtclmnNote;*/
            //_currentinvoiceitems.Add(



            invoiceitems2 newrow = new invoiceitems2();
            InvoiceControlAccompanyStockAdd ctrl = (InvoiceControlAccompanyStockAdd)sender;
            if (string.IsNullOrEmpty(ctrl.Title) || string.IsNullOrEmpty(ctrl.Amount))
                return;
            int i;
            i = dataGridView1.Rows.Add( new DataGridViewRow());

            DataGridViewCell cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl.Title;
            newrow.title = ctrl.Title;
            dataGridView1.Rows[i].Cells["dtclmnTitle"] = cell1;

            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl.Note;
            newrow.note = ctrl.Note;
            dataGridView1.Rows[i].Cells["dtclmnNote"] = cell1;

           

            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl.Amount;
            newrow.amount = Convert.ToSingle(ctrl.Amount);
            dataGridView1.Rows[i].Cells["dtclmnAmount"] = cell1;

            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = i+1;
            newrow.num = (i + 1).ToString();
            dataGridView1.Rows[i].Cells["dtclmnid"] = cell1;


            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl._Type;
            newrow.type = ctrl._Type;
            dataGridView1.Rows[i].Cells["dttype"] = cell1;

            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl._Typeid;
            newrow.typeid = ctrl._Typeid;
            dataGridView1.Rows[i].Cells["dttypeid"] = cell1;


            DataGridViewButtonCell cell2 = new DataGridViewButtonCell();
            cell2.Value = "מחיקה";
            dataGridView1.Rows[i].Cells["dtbttndelet"] = cell2;

            _currentinvoiceitems.Add(newrow);


            


           /* cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl.Title;
            dataGridView1.Rows[i].Cells["Amount"] = cell1;

            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl.Title;
            dataGridView1.Rows[i].Cells["Title"] = cell1;*/
            
        }
        private void updateTankStock(string tankids,string invoicenumber)
        {
            int tankid = Convert.ToInt32(tankids);

            //  update tankstock 
            using (GazOnDevEntities db = new GazOnDevEntities())
            {
               

                Tank_Stocks edittank = db.Tank_Stocks.SingleOrDefault(x => x.Id == tankid);
                edittank.invoiceid = invoicenumber;
                if (string.IsNullOrEmpty(invoicenumber))
                {
                    edittank.TankSystemStatus = "1";
                }
                else
                {
                    edittank.TankSystemStatus = "4";
                }
                //db.Tank_Stocks.Attach(edittank);
                db.ObjectStateManager.ChangeObjectState(edittank, EntityState.Modified);
                db.SaveChanges();


            }
        
        }
        private void btnupload_Click_1(object sender, EventArgs e)
        {
            InvoiceControlTankStockAdd dd = new InvoiceControlTankStockAdd();
           dd.FormClosing+=new Gizmox.WebGUI.Forms.Form.FormClosingEventHandler(dd2_FormClosing);


            dd.ShowDialog();

        }

        void dd2_FormClosing(object sender, FormClosingEventArgs e)
        {

            InvoiceControlTankStockAdd ctrl = (InvoiceControlTankStockAdd)sender;

            if (string.IsNullOrEmpty(ctrl.TankNumber))
                return;
            int i;
            i = dataGridView1.Rows.Add(new DataGridViewRow());

            DataGridViewCell cell1 = new DataGridViewTextBoxCell();
            cell1.Value = "צובר "+ctrl.tankSize+" גלון מספר "+ctrl.TankNumber+"";
            dataGridView1.Rows[i].Cells["dtclmnTitle"] = cell1;

            invoiceitems2 newrow = new invoiceitems2();


            newrow.title = "צובר " + ctrl.tankSize + " גלון מספר " + ctrl.TankNumber + "";

         

            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl.Note;
            newrow.note = ctrl.Note;
            dataGridView1.Rows[i].Cells["dtclmnNote"] = cell1;



            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl._Amount;
            newrow.amount = Convert.ToInt32(ctrl._Amount);
            dataGridView1.Rows[i].Cells["dtclmnAmount"] = cell1;

            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = i + 1;
            newrow.num = (i + 1).ToString();
            dataGridView1.Rows[i].Cells["dtclmnid"] = cell1;


            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl._Type;
            newrow.type = ctrl._Type;
            dataGridView1.Rows[i].Cells["dttype"] = cell1;

            cell1 = new DataGridViewTextBoxCell();
            cell1.Value = ctrl._Typeid;
            newrow.typeid = ctrl._Typeid;
            dataGridView1.Rows[i].Cells["dttypeid"] = cell1;

            _currentinvoiceitems.Add(newrow);

            if (ctrl._Type == "tank")
            {
                if (null == _currentinvoice)
                {
                    updateTankStock(ctrl._Typeid, txtinvoiceid.Text);
                
                }
                else
                {
                    updateTankStock(ctrl._Typeid, _currentinvoice.invoiceNumber);
                }
                    havetank = true;
                
            }
           
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if(null != _currentinvoice)
            {
                 // MessageBox.Show("פעולת ההוספה הצליחה");
            frmReportTankRecipet tanko = new frmReportTankRecipet(Convert.ToInt32(_currentinvoice.invoiceNumber), "report4");
            tanko.ShowDialog();
            }else
            {
                MessageBox.Show("נא קיים תעודה כזו נא לשמור או לבחור חדשה ");
            }
           
        }

        public EventHandler OnEditButtonClick { get; set; }

    }

}